const Koa = require("koa");
const util = require('util');
const KoaRouter = require("@koa/router");
const app = new Koa();
const router = new KoaRouter();
const exection = util.promisify(require("child_process").execFile);
const path = require("path");
const interfaces = require('os').networkInterfaces();
const fs = require('fs')


app.use(router.routes());

let lockBuild = true;
router.get("/generate", async (ctx, next) => {
  ctx.set("Access-Control-Allow-Origin", "*");
  let params = ctx.query;
  if (lockBuild) {
    lockBuild = false;
    console.log("into");
    const { stdout, stderr } = await exection(
      "bash",
      [`a.sh ${params["type"]} ${' ' + params['version']} ${params['application']}`],
      { shell: true }
    );

    let path = ''
    if (params['application'] == 'enterprise') {
      path = 'check-list-enterprise/enterprise/build/app/outputs/flutter-apk'
    } else if (params['application'] == 'goverment') {
      path = 'check-list-enterprise/goverment/build/app/outputs/flutter-apk'
    } else if (params['application'] == 'aky') {
      path = 'app-aky/enterprise/build/app/outputs/flutter-apk'
    }

    lockBuild = true;
    ctx.body = { code: 200, url: `http://${getIPAdress()}:1027/${path}/app-release.apk` };
  }
  else {
    ctx.body = { code: 201, message: '其他人正在打包，请稍等' }
  }
});

router.get('/down', async (ctx, next) => {
  ctx.set("Access-Control-Allow-Origin", "*");
  let params = ctx.query;

  let path = ''
  if (params['application'] == 'enterprise') {
    path = 'check-list-enterprise/enterprise/build/app/outputs/flutter-apk'
  } else if (params['application'] == 'goverment') {
    path = 'check-list-enterprise/goverment/build/app/outputs/flutter-apk'
  } else if (params['application'] == 'aky') {
    path = 'app-aky/enterprise/build/app/outputs/flutter-apk'
  }
  console.log(params);
  ctx.body = { code: 200, url: `http://${getIPAdress()}:1027/${path}/app-release.apk` };
});

router.get('/version', async (ctx, next) => {
  ctx.set("Access-Control-Allow-Origin", "*");
  let params = ctx.query;
  const data = fs.readFileSync('version.txt', 'utf8')
  ctx.body = {
    code: 200, message: [
      data.split('\n')[0],
      data.split('\n')[1],
    ]
  }
})

router.post('/test',async (ctx, next)=>{
  ctx.set("Access-Control-Allow-Origin", "*");
  // let data = await parseData(ctx)
  let str = ''
  ctx.req.on('data', (data) => {
    str += data
})
ctx.req.addListener('end', () => {
    console.log(str);
})
  ctx.body = 'aaa'
})

function parseData(ctx) {
  return new Promise((resolve, reject) => {
      try {
          let str = ''
          ctx.req.on('data', (data) => {
              str += data
          })
          ctx.req.addListener('end', () => {
              resolve(parseUrl(str))
          })
      } catch (err) {
          reject(err)
      }
  });
}

function getIPAdress() {
  for (var devName in interfaces) {
    var iface = interfaces[devName];
    for (var i = 0; i < iface.length; i++) {
      var alias = iface[i];
      if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
        return alias.address;
      }
    }
  }
}


app.listen(8081);
